<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Authenticate
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $result_arr = null;
        $sid = $request->header('sid');
        if($sid == null) $sid = $request->input('sid');
        if(empty($sid)){
            $result_arr = array(
                'code'=>401,
                'message'=>'请登录'
            );
            return response()->json($result_arr);
        }else{
            $db = \MyDB::getInstance();
            $user = $db->findOne("select * from users where sid='$sid'", []); //DB::table('users')->where("sid", "=", $sid)->first();
            if($user == null){
                $result_arr = array(
                    'code'=>401,
                    'message'=>'无效token，请重新登录'
                );
                return response()->json($result_arr);
            }else{
                return $next($request);
            }
        }


    }
}
